#include "serialportwidget.h"
#include "ui_serialportwidget.h"

SerialPortWidget::SerialPortWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::SerialPortWidget)
{
    ui->setupUi(this);
    loadStyleSheet("C:/Users/shafl/Desktop/FrameWork/css/img.css");
    m_pSerialPort = new QSerialPort(this);
    initialization();
    connect(ui->btnOpen,&QPushButton::clicked,this,&SerialPortWidget::onOpenSerialPort);
}

SerialPortWidget::~SerialPortWidget()
{
    delete ui;
}

void SerialPortWidget::loadStyleSheet(const QString &CssPath)
{
    QFile file(CssPath);
    if(!file.open(QIODevice::ReadWrite)){
        qDebug() << "open file failed";
        return;
    }
    this->setStyleSheet(file.readAll());
}

void SerialPortWidget::initialization()
{
    m_isOpend = false;

    QList<QSerialPortInfo> portlist = QSerialPortInfo::availablePorts();
    for(auto &serialport : portlist){
        ui->comboBoxSerialPort->addItem(serialport.portName()+"-"+serialport.description(),serialport.portName());
    }

    QList<QPair<QString,QSerialPort::BaudRate>> baudRates{
        {"1200",QSerialPort::Baud1200},
        {"2400",QSerialPort::Baud2400},
        {"4800",QSerialPort::Baud4800},
        {"9600",QSerialPort::Baud9600},
        {"19200",QSerialPort::Baud19200},
        {"38400",QSerialPort::Baud38400},
        {"57600",QSerialPort::Baud57600},
        {"115200",QSerialPort::Baud115200}
    };
    for(const auto &baudRate : baudRates){
        ui->comboBoxBaudRate->addItem(baudRate.first,baudRate.second);
    }

    QList<QPair<QString,QSerialPort::DataBits>> dataBits{
        {"8",QSerialPort::DataBits::Data8},
        {"7",QSerialPort::DataBits::Data7},
        {"6",QSerialPort::DataBits::Data6},
        {"5",QSerialPort::DataBits::Data5},
    };
    for(const auto &dataBit : dataBits){
        ui->comboBoxDataByte->addItem(dataBit.first,dataBit.second);
    }

    QList<QPair<QString,QSerialPort::Parity>> parityBits{
        {"NONE",QSerialPort::Parity::NoParity},
        {"ODD",QSerialPort::Parity::OddParity},
        {"EVEN",QSerialPort::Parity::EvenParity},
        {"MARK",QSerialPort::Parity::MarkParity},
        {"SPACE",QSerialPort::Parity::SpaceParity}
    };
    for(const auto &parityBit : parityBits){
        ui->comboBoxParity->addItem(parityBit.first,parityBit.second);
    }

    QList<QPair<QString,QSerialPort::StopBits>> stopBits{
        {"1",QSerialPort::StopBits::OneStop},
        {"1.5",QSerialPort::StopBits::OneAndHalfStop},
        {"2",QSerialPort::StopBits::TwoStop},
    };
    for(const auto &stopBit : stopBits){
        ui->comboBoxStopByte->addItem(stopBit.first,stopBit.second);
    }

}

void SerialPortWidget::onOpenSerialPort()
{
    if(m_isOpend){
        ui->comboBoxParity->setEnabled(true);
        ui->comboBoxBaudRate->setEnabled(true);
        ui->comboBoxDataByte->setEnabled(true);
        ui->comboBoxStopByte->setEnabled(true);
        ui->comboBoxStreamCtl->setEnabled(true);
        ui->comboBoxSerialPort->setEnabled(true);

        m_isOpend = false;
        emit sendMessage("串口关闭成功");
        ui->btnOpen->setText("打开串口");
        disconnect(m_pSerialPort,&QIODevice::readyRead,this,&SerialPortWidget::onRecvData);
        disconnect(ui->btnSend,&QPushButton::clicked,this,&SerialPortWidget::onSendData);
        m_pSerialPort->close();
        return;
    }
    else{
        m_pSerialPort->setPortName(ui->comboBoxSerialPort->currentData().toString());
        m_pSerialPort->setBaudRate((QSerialPort::BaudRate)ui->comboBoxBaudRate->currentData().toInt());
        m_pSerialPort->setDataBits((QSerialPort::DataBits)ui->comboBoxDataByte->currentData().toInt());
        m_pSerialPort->setParity((QSerialPort::Parity)ui->comboBoxParity->currentData().toInt());
        m_pSerialPort->setStopBits((QSerialPort::StopBits)ui->comboBoxStopByte->currentData().toInt());

        if(!m_pSerialPort->open(QIODevice::ReadWrite)){
            qDebug()<<"串口打开失败";
            emit sendMessage("串口打开失败");
            return;
        }
        qDebug()<<"串口打开成功";
        ui->comboBoxParity->setEnabled(false);
        ui->comboBoxBaudRate->setEnabled(false);
        ui->comboBoxDataByte->setEnabled(false);
        ui->comboBoxStopByte->setEnabled(false);
        ui->comboBoxStreamCtl->setEnabled(false);
        ui->comboBoxSerialPort->setEnabled(false);
        m_isOpend = true;
        emit sendMessage("串口打开成功");
        //串口信号和槽函数关联
        connect(m_pSerialPort,&QIODevice::readyRead,this,&SerialPortWidget::onRecvData);
        connect(ui->btnSend,&QPushButton::clicked,this,&SerialPortWidget::onSendData);
        ui->btnOpen->setText("关闭串口");
    }
}

void SerialPortWidget::onRecvData()
{
    //取出新来的数据
    QByteArray buff = m_pSerialPort->readAll();;
    //取出的数据放入TextEdit
    if(!buff.isEmpty())
    {
        ui->textEditRecvArea->append("[Received] "+buff);
    }
}

void SerialPortWidget::onSendData()
{
    if (!m_pSerialPort->isOpen()) {
        qDebug() << "串口未打开！";
        emit sendMessage("串口未打开！");
        return;
    }
    QByteArray data = ui->textEditSendArea->toPlainText().toUtf8();
    data.replace("\n", "\r\n");
    qint64 bytesWritten = m_pSerialPort->write(data);

    if (bytesWritten == -1) {
        qDebug() << "发送失败：" << m_pSerialPort->errorString();
        emit sendMessage("发送失败：" + m_pSerialPort->errorString());
    } else if (bytesWritten != data.size()) {
        qDebug() << "数据未全部发送，已发送：" << bytesWritten << "字节";
        emit sendMessage("数据未全部发送");
    } else {
        qDebug() << "数据发送成功：" << data;
        emit sendMessage("数据发送成功");
    }
    // 确保数据被立即发送（刷新缓冲区）
    m_pSerialPort->flush();
}


